package com.lvmama.rhino.web;

import com.github.pagehelper.PageInfo;
import com.lvmama.rhino.enums.EnumForCategory;
import com.lvmama.rhino.enums.NpsQuestionTypeEnum;
import com.lvmama.rhino.enums.OrderTypeEnum;
import com.lvmama.rhino.pojo.NPSCommit;
import com.lvmama.rhino.pojo.NPSCommitQuery;
import com.lvmama.rhino.pojo.NPSStatistics;
import com.lvmama.rhino.service.NPSService;
import com.lvmama.rhino.utils.ExportCSVUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author:caoyong
 * @Description: NPS问卷后台
 * @Date：2017/10/18
 */
@Controller
@RequestMapping("npsQuestionnaire")
public class NPSQuestionnaireController {
    private Logger log = Logger.getLogger(NPSQuestionnaireController.class);
    @Autowired
    private NPSService npsService;

    /**
     * 查询nps问卷后台
     *
     * @param model 数据模型
     * @return 视图名
     */
    @RequestMapping("getQuestionnaireList")
    public String getQuestionnaireList(Model model) {
        log.info("getQuestionnaireList start");
        try {
            // 品类
            model.addAttribute("categories", EnumForCategory.getAllCategory());
            model.addAttribute("orderTypes", OrderTypeEnum.values());
            model.addAttribute("npsQuestionTypes", NpsQuestionTypeEnum.values());
        } catch (Exception e) {
            log.error("getQuestionnaireList error:" + e.getMessage(), e);
        }
        log.info("getQuestionnaireList end.");
        return "application/nps/npsQuestionnaire";
    }

    /**
     * 查询nps分页
     *
     * @param query 查询条件
     * @return 分页
     */
    @RequestMapping("list")
    @ResponseBody
    public PageInfo<NPSCommit> list(NPSCommitQuery query) {
        PageInfo<NPSCommit> pageInfo = null;
        log.info("get list start. query:{}" + query);
        try {
            if (NpsQuestionTypeEnum.INTERNAL.getCode().equals(query.getNpsQuestionType())) {
                pageInfo = npsService.queryNPSInternalCommitPage(query);
            } else {
                pageInfo = npsService.queryNPSCommitPage(query);
            }
        } catch (Exception e) {
            log.error("get list error:" + e.getMessage(), e);
        }
        log.info("get list end.");
        return pageInfo;
    }

    /**
     * 查询nps统计数据
     *
     * @param query 查询条件
     * @return 结果
     */
    @RequestMapping("npsStatistics")
    @ResponseBody
    public NPSStatistics npsStatistics(NPSCommitQuery query) {
        NPSStatistics statistics = null;
        log.info("get npsStatistics start. query:{}" + query);
        try {
            if (NpsQuestionTypeEnum.INTERNAL.getCode().equals(query.getNpsQuestionType())) {
                statistics = npsService.queryNpsInternalStatistics(query);
            } else {
                statistics = npsService.queryNpsStatistics(query).get(0);
            }
        } catch (Exception e) {
            log.error("get npsStatistics error:" + e.getMessage(), e);
        }
        log.info("get npsStatistics end.");
        return statistics;
    }

    /**
     * 导出问卷查询内容到excel
     *
     * @param query 查询条件
     */
    @RequestMapping("exportQuestionnaire")
    public void exportQuestionnaire(NPSCommitQuery query, HttpServletResponse response) {
        List<NPSCommit> commits;
        log.info("exportQuestionnaire start. query:" + query);
        try {
            String fileName;
            if (NpsQuestionTypeEnum.INTERNAL.getCode().equals(query.getNpsQuestionType())) {
                commits = npsService.queryNPSInternalCommitList(query);
                fileName = URLEncoder.encode("NPS问卷统计-内部", "UTF-8");
            } else {
                commits = npsService.queryNPSCommitList(query);
                fileName = URLEncoder.encode("NPS问卷统计-外部", "UTF-8");
            }

            // 生成提示信息
            response.setContentType("application/octet-stream");
            // 进行转码，使其支持中文文件名

            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
            BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "gbk"), 1024);

            String[] headers;
            if (NpsQuestionTypeEnum.INTERNAL.getCode().equals(query.getNpsQuestionType())) {
                headers = new String[]{"编号", "提交时间", "分值", "备注"};
            } else {
                headers = new String[]{"编号", "提交时间", "会员ID", "手机号", "品类", "订单ID", "提交时状态", "分值", "备注"};
            }
            Field[] fields = getFieldsSearch(headers, query.getNpsQuestionType());
            ExportCSVUtils<NPSCommit> exportCSVUtils = new ExportCSVUtils<>();
            exportCSVUtils.exportCSV(headers, fields, commits, bf, "yyyy-MM-dd HH:mm:ss");

            if (null != commits) {
                log.info("总共导出数据：" + commits.size() + "条");
            }
        } catch (Exception e) {
            log.error("exportQuestionnaire error:" + e.getMessage(), e);
        }
        log.info("exportQuestionnaire end.");
    }

    /**
     * 根据每列字段名称创建需要导出字段的数组
     *
     * @param headers 表头
     * @return 字段数组
     */
    private Field[] getFieldsSearch(String[] headers, String npsQuestionType) {
        Field[] fields = new Field[headers.length];
        NPSCommit t = new NPSCommit();
        try {
            for (int i = 0; i < headers.length; i++) {
                if (NpsQuestionTypeEnum.INTERNAL.getCode().equals(npsQuestionType)) {
                    switch (headers[i]) {
                        case "编号":
                            fields[i] = t.getClass().getDeclaredField("id");
                            break;
                        case "提交时间":
                            fields[i] = t.getClass().getDeclaredField("commitTime");
                            break;
                        case "分值":
                            fields[i] = t.getClass().getDeclaredField("score");
                            break;
                        case "备注":
                            fields[i] = t.getClass().getDeclaredField("originRemark");
                            break;
                    }
                } else {
                    switch (headers[i]) {
                        case "编号":
                            fields[i] = t.getClass().getDeclaredField("id");
                            break;
                        case "提交时间":
                            fields[i] = t.getClass().getDeclaredField("commitTime");
                            break;
                        case "会员ID":
                            fields[i] = t.getClass().getDeclaredField("userId");
                            break;
                        case "手机号":
                            fields[i] = t.getClass().getDeclaredField("phoneNumber");
                            break;
                        case "品类":
                            fields[i] = t.getClass().getDeclaredField("categoryName");
                            break;
                        case "订单ID":
                            fields[i] = t.getClass().getDeclaredField("orderId");
                            break;
                        case "提交时状态":
                            fields[i] = t.getClass().getDeclaredField("commitType");
                            break;
                        case "分值":
                            fields[i] = t.getClass().getDeclaredField("score");
                            break;
                        case "备注":
                            fields[i] = t.getClass().getDeclaredField("originRemark");
                            break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fields;
    }

    @RequestMapping("pushEmail")
    @ResponseBody
    public boolean pushEmail() {
        log.info("pushEmail start.");
        try {
            boolean flag = npsService.sendNPSEmail();
            log.info("pushEmail is:" + flag);
            return flag;
        } catch (Exception e) {
            log.error("pushEmail error:" + e.getMessage(), e);
        }
        log.info("pushEmail end.");
        return false;
    }
}
